package com.team6.yygh.order.api;

import com.team6.yygh.order.service.PaymentService;
import com.team6.yygh.order.service.WeixinService;
import com.team6.yygh.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @ClassName WeixinController
 * @Author ZhuYouWan
 * @Date 2022/10/28 13:52
 **/
@Api(tags = "微信支付")
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;
    @Autowired
    private PaymentService paymentService;

    /**
     * 生成微信支付二维码
     */
    @ApiOperation(value = "生成微信支付二维码")
    @GetMapping("/createNative/{orderId}")
    public Result createNative(@PathVariable Long orderId){
        Map map = weixinService.createNative(orderId);
        return Result.ok(map);
    }

    /**
     * 查询支付状态
     */
    @ApiOperation(value = "查询支付状态")
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId){
        // 调用微信接口实现支付状态查询
        Map<String, String> resultMap = weixinService.queryPayStatus(orderId);
        // 判断
        if (resultMap == null) {
            return Result.fail().message("支付错误");
        }
        // 支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))){
            // 更新订单状态
            String outTradeNo = resultMap.get("out_trade_no");
            paymentService.paySuccess(outTradeNo, resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}
